package main

import (
	"fmt"
	"github.com/hashicorp/consul/api"
	uuid "github.com/satori/go.uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"net"
	"os"
	"os/signal"
	"project06_src/src/global"
	"project06_src/src/handler"
	"project06_src/src/initalize"
	"project06_src/src/proto"
	"syscall"
)

func main() {
	initalize.InitDb()
	initalize.InitConfig()

	server := grpc.NewServer()

	proto.RegisterSubscribeServiceServer(server, &handler.SubscribeService{})

	grpc_health_v1.RegisterHealthServer(server, health.NewServer())

	cfg := api.DefaultConfig()
	cfg.Address = fmt.Sprintf("%s:%d", global.SrvConf.ConsulConf.Host, global.SrvConf.ConsulConf.Port)
	client, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}
	check := api.AgentServiceCheck{
		GRPC:                           fmt.Sprintf("%s:%d", global.SrvConf.Host, global.SrvConf.Port), //要更改
		Timeout:                        "5s",
		Interval:                       "5s",
		DeregisterCriticalServiceAfter: "10s",
	}

	registion := new(api.AgentServiceRegistration)
	registion.Address = global.SrvConf.ConsulConf.Host
	registion.Name = global.SrvConf.Name
	myUuid := fmt.Sprintf("%s", uuid.NewV4())
	registion.ID = myUuid
	registion.Port = global.SrvConf.Port
	registion.Check = &check

	err = client.Agent().ServiceRegister(registion)
	if err != nil {
		panic(err)
	}

	lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d",
		global.SrvConf.Host,
		global.SrvConf.Port))
	if err != nil {
		panic(err)
	}

	go func() {
		err = server.Serve(lis)
		if err != nil {
			fmt.Println("server.Serve err", err)
			return
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = client.Agent().ServiceDeregister(myUuid); err != nil {
		fmt.Println("注销失败")
	}
	fmt.Println("注销成功")

}
